<?php

namespace app\admin\controller\mall;

use app\admin\model\MallAddress;
use app\admin\model\MallTradeRecordLog;
use app\admin\model\MallUser;
use app\admin\model\MallWithdrawRecord;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use app\common\controller\AdminController;
use jianyan\excel\Excel;
use think\App;

/**
 * @ControllerAnnotation(title="用户管理")
 */
class User extends AdminController
{
    
    
    public function __construct(App $app)
    {
        parent::__construct($app);
        
        $this->model = new \app\admin\model\MallUser();
        
        $this->assign('getStatusList', $this->model->getStatusList());
        
    }
    /**
     * @NodeAnotation(title="列表")
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            [$page, $limit, $where] = $this->buildTableParames();
            $where[] = ['ea_mall_user.is_virtual', '=', 0];
            $count   = $this->model
                ->withJoin(['promotion'], 'left')
                ->where($where)
                ->count();
            $list    = $this->model
                ->withJoin(['promotion'], 'left')
                ->where($where)
                ->page($page, $limit)
                ->order($this->sort)
                ->select()->toArray();
            $userIds = array_column($list, 'id');
            $trade   = MallTradeRecordLog::where([['user_id', 'in', $userIds]])->field('trade_type,SUM(amount) as amount,user_id')->group('user_id,trade_type')->select();;
            foreach ($list as $key => &$value) {
                $value[ 'consume_amount' ]        = 0;
                $value[ 'success_reward_amount' ] = 0;
                $value[ 'withdraw_amount' ]       = 0;
                $value[ 'failure_reward_amount' ] = 0;
                $value[ 'promotion' ][ 'name' ]   = $value[ 'promotion' ][ 'name' ] ?? '';
                foreach ($trade as $k => $v) {
                    if ($value[ 'id' ] == $v[ 'user_id' ]) {
                        switch ($v[ 'trade_type' ]) {
                            case 1:
                                $value[ 'consume_amount' ] += $v[ 'amount' ];
                                break;
                            case 3:
                                $value[ 'failure_reward_amount' ] += $v[ 'amount' ];
                                break;
                            case 14:
                            case 15:
                            case 16:
                                $value[ 'withdraw_amount' ] += $v[ 'amount' ];
                                break;
                            case 6:
                                $value[ 'withdraw_amount' ] -= $v[ 'amount' ];
                                break;
                            case 7:
                                $value[ 'success_reward_amount' ] += $v[ 'amount' ];
                                break;
                            case 10:
                            case 12:
                                $value[ 'consume_amount' ] -= $v[ 'amount' ];
                                break;
                        }
                    }
                }
            }
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }
    
    
    /**
     * @NodeAnotation(title="属性修改")
     */
    public function modify()
    {
        $this->checkPostRequest();
        $post = $this->request->post();
        $rule = [
            'id|ID'    => 'require',
            'field|字段' => 'require',
            'value|值'  => 'require',
        ];
        $this->validate($post, $rule);
        $row = $this->model->find($post[ 'id' ]);
        if ( !$row) {
            $this->error('数据不存在');
        }
        try {
            $row->save([
                $post[ 'field' ] => $post[ 'value' ],
            ]);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('保存成功');
    }
    /**
     * @NodeAnotation(title="提现记录")
     */
    public function withdraw()
    {
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            [$page, $limit, $where] = $this->buildTableParames();
            $where[] = ['user_id', '=', input('id')];
            $count   = MallWithdrawRecord::where($where)
                ->count();
            $list    = MallWithdrawRecord::where($where)
                ->page($page, $limit)
                ->order($this->sort)
                ->select()
                ->toArray();
            $data    = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        $this->assign('id', input('id'));
        return $this->fetch();
    }
    /**
     * @NodeAnotation(title="奖励记录")
     */
    public function reward()
    {
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            [$page, $limit, $where] = $this->buildTableParames();
            $where[] = ['ea_mall_trade_record_log.user_id', '=', input('id')];
            $where[] = ['trade_type', '=', 3];
            $count   = MallTradeRecordLog::where($where)
                ->count();
            $list    = MallTradeRecordLog::where($where)
                ->withJoin('mallOrder', 'LEFT')
                ->page($page, $limit)
                ->order($this->sort)
                ->select()
                ->toArray();
            $data    = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        $this->assign('id', input('id'));
        return $this->fetch();
    }
    /**
     * @NodeAnotation(title="地址管理")
     */
    public function address()
    {
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            [$page, $limit, $where] = $this->buildTableParames();
            $where[]   = ['ea_mall_address.user_id', '=', input('id')];
            $addressId = MallUser::where('id', input('id'))->value('address_id');
            $count     = MallAddress::where($where)
                ->count();
            $list      = MallAddress::where($where)
                ->page($page, $limit)
                ->order($this->sort)
                ->select()
                ->toArray();
            foreach ($list as $key => $value) {
                $list[ $key ][ 'current' ] = 0;
                if ($value[ 'id' ] == $addressId) {
                    $list[ $key ][ 'current' ] = 1;
                }
            }
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        $this->assign('id', input('id'));
        return $this->fetch();
    }
    
    /**
     * @NodeAnotation(title="设置推广人")
     */
    public function promotion($id)
    {
        $row = $this->model->find($id);
        empty($row) && $this->error('数据不存在');
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $rule = [];
            $this->validate($post, $rule);
            try {
                $post[ 'promotion_time' ] = time();
                $save                     = $row->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        $this->assign('row', $row);
        return $this->fetch();
    }
//    /**
//     * @NodeAnotation(title="导出")
//     */
//    public function export()
//    {
//        [$page, $limit, $where] = $this->buildTableParames();
//        $header   = [
//            ['用户id', 'id'],
//            ['姓名', 'name'],
//            ['电话号码', 'mobile'],
//            ['头像', 'avatar_url'],
//            ['实际消费的金额(不含退款)', 'expend_money'],
//            ['登录IP', 'login_ip'],
//            ['创建时间', 'create_time'],
//        ];
//        $list     = $this->model
//            ->where($where)
//            ->limit(100000)
//            ->order('id', 'desc')
//            ->select()
//            ->toArray();
//        $fileName = '用户列表' . time();
//        return Excel::exportData($list, $header, $fileName, 'xlsx');
//    }
    
}